package org.jiucheng.magpiebridge.server.aio.proxy.http11;

import java.nio.ByteBuffer;
import java.nio.channels.CompletionHandler;
import java.text.MessageFormat;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.jiucheng.magpiebridge.protocol.Message;
import org.jiucheng.magpiebridge.server.aio.ServerAttachment;
import org.jiucheng.magpiebridge.server.aio.ServerWriteNoProxyClientReadCompletionHandler;
import org.jiucheng.magpiebridge.server.aio.proxy.ProxyAttachment;
import org.jiucheng.magpiebridge.server.util.Container;

public class Http11ProxyReadCompletionHandler implements CompletionHandler<Integer, Http11ProxyAttachment> {
    
    private static final Logger LOGGER = Logger.getLogger(Http11ProxyReadCompletionHandler.class.getName());

	public void completed(Integer result, Http11ProxyAttachment attachment) {
		if (result != -1) {
			ByteBuffer readBuffer = attachment.getReadBuffer();
	        byte[] data = new byte[readBuffer.position()];
	        readBuffer.flip();
	        readBuffer.get(data);
	        String req = new String(data);
	        if (LOGGER.isLoggable(Level.FINE)) {
	            LOGGER.log(Level.FINE, req);
	        }
	        String[] lines = req.split("\r\n");
	        String firstLine = lines[0];
	        if (!(firstLine.endsWith("HTTP/1.1") || firstLine.endsWith("HTTP/1.0"))) {
	            if (LOGGER.isLoggable(Level.FINE)) {
	                LOGGER.log(Level.FINE, "httpproxy close 1");
	            }
	        	attachment.close();
	        	return;
	        }
	        for (int i = 1; i < lines.length; i++) {
	        	String line = lines[i];
	        	if (line.startsWith("Host: ")) {
	        		// 域名
	        		String domain = line.substring(6);
	                if (LOGGER.isLoggable(Level.FINE)) {
	                    LOGGER.log(Level.FINE, MessageFormat.format("domain={0}", domain));
	                }
					List<Object> item = Container.DOMAINS.get(domain);
					if (item != null) {
						ServerAttachment serverAttachment = (ServerAttachment) item.get(0);
						String remote = (String) item.get(1);
						
                        Message message = new Message();
                        message.setMagic(Message.MAGIC);
                        message.setType(Message.Type.CONNECT);
                        message.setUri(Container.CLIENTS_ID.incrementAndGet());
                        byte[] datas = remote.getBytes();
                        message.setData(datas);
                        message.setSize(datas.length);
                        ByteBuffer writeBuffer = Message.toByteBuffer(message);
                        
                        if (LOGGER.isLoggable(Level.FINE)) {
                            LOGGER.log(Level.FINE, MessageFormat.format("domain={0},uri={1},remote={1}", domain, message.getUri(), remote));
                        }
                        
                        readBuffer.position(data.length);
				        if (serverAttachment.canWrited()) {
				            ServerAttachment.proxys.put(message.getUri(), new ProxyAttachment(attachment.getServer()).setReadBuffer(readBuffer).setUri(message.getUri()).setServerAttachment(serverAttachment));
				            serverAttachment.getServer().write(writeBuffer, serverAttachment.setWriteBuffer(writeBuffer), new ServerWriteNoProxyClientReadCompletionHandler());
				        }
						return;
					}
	        		break;
	        	}
	        }
		}
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, "httpproxy close 2");
        }
        attachment.close();
	}

	public void failed(Throwable exc, Http11ProxyAttachment attachment) {
        if (LOGGER.isLoggable(Level.SEVERE)) {
            LOGGER.log(Level.SEVERE, "httpproxy", exc);
        }
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, "httpproxy close 3");
        }
		attachment.close();
	}
}
